
//检测关键词
#include <stdio.h>
#include "include/snowboy-detect-c-wrapper.h"  //snowboy 
#include  <alsa/asoundlib.h>                 //alsa
#include  <signal.h>                         //signal
#include <stdlib.h>
#define NUM_FRAMES 1600

int interrupted=0;
void handle_sigint(int signo)
{
	interrupted=1;
}

//打开录音设备
snd_pcm_t * open_recorder( const char * name)
{

	snd_pcm_t * mic=NULL;
	//1.打开默认的音频设备
	int error=snd_pcm_open(&mic,"sysdefault",SND_PCM_STREAM_CAPTURE,0);

	if(error!=0)
	{
		perror("snd_pcm_open failed");
		return NULL;
	}

	//2.设置硬件参数
	snd_pcm_hw_params_t * hw_params;

	//分配硬件参数内存
	snd_pcm_hw_params_alloca(&hw_params);

	//初始化硬件参数,使用默认值
	snd_pcm_hw_params_any(mic,hw_params);

	//多声道交错存储,读写方式
	snd_pcm_hw_params_set_access(mic,hw_params,SND_PCM_ACCESS_RW_INTERLEAVED);

	//设置采样格式,有符号16位整数,小端字节序
	
	snd_pcm_hw_params_set_format(mic,hw_params,SND_PCM_FORMAT_S16_LE);

	//设置采样率:16000HZ
	snd_pcm_hw_params_set_rate(mic,hw_params,16000,0);

	//设置声道数:单声道
	
	snd_pcm_hw_params_set_channels(mic,hw_params,1);

	

	//根据硬件参数设置声卡设备
	error=snd_pcm_hw_params(mic,hw_params);

	if(error!=0)
	{
		perror("snd_pcm_open failed\n");
		return NULL;
	}

	return mic;	

}


//关闭声音设备

void close_recorder(snd_pcm_t * mic)
{
	snd_pcm_drain(mic); //停止往缓冲区放,想读取还可以
	snd_pcm_close(mic);
}


//开始录音

int start_recording(snd_pcm_t * mic)
{

	return snd_pcm_prepare(mic);
}


//停止录音
int stop_recording(snd_pcm_t * mic)
{
	return snd_pcm_drop(mic);//立即停止接受
}


int main(void)
{


	//参数1：资源文件的文件名
	//参数2: 唤醒词模型:  snowboy / 
	SnowboyDetect * detector=SnowboyDetectConstructor("common.res","xiaohua.umdl");
	//设置灵敏度	
	SnowboyDetectSetSensitivity(detector,"0.5");

	//设置音频声音增益
	SnowboyDetectSetAudioGain(detector,1);


	//设置信号处理函数
	signal(SIGINT,handle_sigint);


	snd_pcm_t * mic=open_recorder("sysdefault");

	if(mic==NULL)
	{
		return -1;
	}



	//将桢数转成字节数
	//
	char * buf=malloc(snd_pcm_frames_to_bytes(mic,NUM_FRAMES));

	start_recording(mic);
	while(interrupted!=1)
	{
		//每次0.1秒的音频数据,16000Hz,1600个采样点
		//一个采样点2字节，3200字节
		//0.1秒的数据占用的空间
		snd_pcm_sframes_t frames=snd_pcm_readi(mic,buf,NUM_FRAMES);

		//返回值>0检测到关键词
		//＝0     有声音但不是关键词
		//=-1  出错
		//=-2 没有声音
		//发给snowboy
		int result=SnowboyDetectRunDetection(detector,(int16_t  *)buf,frames,0);

		printf("result=%d\n",result);
	}
	

	


	close_recorder(mic);
	//snow的释放
	SnowboyDetectDestructor(detector);






	return 0;
}
